#ifndef __EVENTLOOP_H__
#define __EVENTLOOP_H__

#include "MutexLock.hpp"

#include <sys/epoll.h>

#include <memory>
#include <functional>
#include <vector>
#include <map>

using std::vector;
using std::map;
using std::pair;
using std::function;
using std::shared_ptr;

namespace cdm{

class TCPConnection;
using TCPConnectionPtr  = shared_ptr<TCPConnection>;
using TCPCallback = function<void(TCPConnectionPtr)>;
using Functor = function<void()>;

class Acceptor;

class EventLoop{

public:
    EventLoop(Acceptor &);
    ~EventLoop();
    void    loop();
    void    unloop();
    void    runInLoop(Functor &&fc);
    void    setAllCallback(TCPCallback &&cb1,TCPCallback &&cb2,TCPCallback &&cb3){
        _onConnection = std::move(cb1);
        _onMessage = std::move(cb2);
        _onClose  = std::move(cb3);
    }

private:
    int  createEpollFd();
    void addEpollReadEvent(int);
    void delEpollReadEvent(int);
    void waitEpollFd();
    void handleNewConnection();
    void handleMessage(int);

    int  createEventFd();
    void handleReadEvent();
    void wakeUp();
    void doPendingFunctors();

private:
    //实际上就是把epoll的循环用类来封装
    int                         _epfd;//epoll的id
    Acceptor&                   _accept;
    bool                        _isLoop;
    vector<struct epoll_event>  _eventArr;
    map<int,TCPConnectionPtr>   _tcpConns;
    TCPCallback                 _onConnection;
    TCPCallback                 _onMessage;
    TCPCallback                 _onClose;
    int                         _eventFd;
    vector<Functor>             _Functors;
    MutexLock                   _mutex;


};

}//end of namespace

#endif


